<template>
	<a-layout class="order-history">
		<a-layout-content style="background: #fff">
			<a-page-header>
				<template v-slot:title>历史订单</template>
				<template slot="extra">
					<a-button @click="reload()" v-has="'order.query'">
						<a-icon type="reload" />
					</a-button>
					<a-button type="primary" @click="exportTable" v-has="'order.export'">
						<a-icon type="export" />
						导出
					</a-button>
				</template>
				<!-- <template slot="title"> {{ $route.meta.title }} </template> -->
			</a-page-header>

			<a-card :bordered="false">
				<a-form-model layout="inline">
					<!-- <a-form class="form" layout="inline">
				<a-row> -->

					<a-form-model-item ref="order_no" label="订单号" prop="order_no">
						<a-input placeholder="订单号" v-model.trim="queryForm.order_no" />
					</a-form-model-item>

					<a-form-model-item
						ref="merchant_name"
						label="商户名"
						prop="merchant_name"
					>
						<a-input
							v-model.trim="queryForm.merchant_name"
							placeholder="商户名"
						/>
					</a-form-model-item>

					<!-- <a-form-model-item
						ref="market_id"
						label="所属批发市场"
						prop="market_id"
						:label-col="{}"
					>
						<a-input
							v-model.trim="queryForm.market_id"
							placeholder="批发市场"
						/>
					</a-form-model-item> -->

					<a-form-model-item label="所属市场">
						<a-select
							allowClear
							v-model="queryForm.market_id"
							style="width: 140px"
							@change="handleMarketChange"
							placeholder="请选择市场"
						>
							<a-select-option
								v-for="(item, index) in marketData"
								:key="index"
								:value="item.id"
							>
								{{ item.name }}
							</a-select-option>
						</a-select>
					</a-form-model-item>

					<!-- </a-row> -->

					<!-- <a-row> -->
					<!-- <a-form-model-item ref="orderId" label="订单类型" prop="name">
						<a-input v-model.trim="queryForm.orderId" placeholder="订单类型" />
					</a-form-model-item> -->

					<a-form-model-item ref="ptype" label="订单类型">
						<a-select
							style="width: 120px"
							v-model.trim="queryForm.ptype"
							placeholder="请选择类型"
							allow-clear
							@change="search"
						>
							<a-select-option :value="1"> 场内转运 </a-select-option>
							<a-select-option :value="2"> 场内装卸 </a-select-option>
							<a-select-option :value="3"> 同城配送 </a-select-option>
							<!-- <a-select-option :value="4"> 配送中 </a-select-option>
							<a-select-option :value="5"> 已完成 </a-select-option> -->
						</a-select>
					</a-form-model-item>

					<a-form-model-item label="订单状态">
						<a-select
							style="width: 120px"
							v-model.trim="queryForm.status"
							placeholder="请选择状态"
							allow-clear
							@change="search"
						>
							<a-select-option :value="-1"> 已取消 </a-select-option>
							<a-select-option :value="0"> 已下单 </a-select-option>
							<a-select-option :value="2"> 已分配 </a-select-option>
							<a-select-option :value="3"> 待揽收 </a-select-option>
							<a-select-option :value="4"> 配送中 </a-select-option>
							<a-select-option :value="5"> 已完成 </a-select-option>
							<a-select-option :value="6"> 已拒收 </a-select-option>
						</a-select>
					</a-form-model-item>

					<a-form-model-item label="支付状态">
						<a-select
							style="width: 120px"
							v-model.trim="queryForm.pay_status"
							placeholder="请选择状态"
							allow-clear
							@change="search"
						>
							<a-select-option :value="-1"> 支付失败 </a-select-option>
							<a-select-option :value="0"> 未支付 </a-select-option>
							<a-select-option :value="1"> 支付成功 </a-select-option>
							<a-select-option :value="2"> 支付中 </a-select-option>
							<a-select-option :value="3">
								上海订单(挂起的订单)
							</a-select-option>
						</a-select>
					</a-form-model-item>

					<a-form-model-item ref="orderId" label="下单时间" prop="name">
						<a-range-picker @change="onChange" v-model="created_at_range">
							<a-icon slot="suffixIcon" type="clock-circle" />
						</a-range-picker>
					</a-form-model-item>

					<a-form-model-item class="operation-button">
						<a-button
							v-has="'order.query'"
							@click="search"
							:disabled="
								Object.values(queryForm).every((item) => {
									return !item
								})
							"
							type="primary"
							icon="search"
							>搜索</a-button
						>
						<a-button
							v-has="'order.query'"
							:disabled="
								Object.values(queryForm).every((item) => {
									return !item
								})
							"
							@click="clear"
							icon="delete"
							style="margin-left: 18px"
							>清空</a-button
						>
					</a-form-model-item>
					<!-- </a-row>
			</a-form> -->
				</a-form-model>
			</a-card>

			<div class="table">
				<!-- 操作栏 -->
				<div class="table-toolBar">
					<a-row type="flex" justify="space-between" align="middle">
						<a-col
							>当前结果：{{ collect.orders }}单，{{ collect.qty }}件，实取{{
								collect.actualQty
							}}件</a-col
						>
						<a-col align="right"
							><a-button shape="circle" icon="arrow-down" />
						</a-col>
					</a-row>
				</div>

				<!-- 表格 -->
				<a-table
					:row-selection="rowSelection"
					:columns="columns"
					:data-source="data"
					:loading="loading"
					:pagination="pagination"
					@change="handleTableChange"
					:rowKey="
						(record, index) => {
							return index
						}
					"
				>
					<!-- 自定义表头内容 -->

					<!-- 自定义单元格列的内容 -->

					<template v-slot:merchant_name="{ merchant_name }">
						<a-tooltip :title="merchant_name" placement="topLeft">
							{{ merchant_name }}
						</a-tooltip>
					</template>

					<template v-slot:market_name="{ market_name }">
						<a-tooltip :title="market_name" placement="topLeft">
							{{ market_name }}
						</a-tooltip>
					</template>

					<template v-slot:map_area_name="{ map_area_name }">
						<a-tooltip :title="map_area_name" placement="topLeft">
							{{ map_area_name }}
						</a-tooltip>
					</template>

					<template v-slot:cpname="{ in_cpname, out_cpname }">
						<a-tooltip :title="in_cpname || out_cpname" placement="topLeft">
							{{ in_cpname || out_cpname }}
						</a-tooltip>
					</template>

					<!-- <span slot="cpname" slot-scope="text, record">
						{{ record.in_cpname || record.out_cpname }}
					</span> -->

					<span slot="pay_status" style="" slot-scope="text, record">{{
						payStatusFilter(record.pay_status)
					}}</span>

					<span slot="status" style="" slot-scope="text, record">{{
						statusFilter(record.status)
					}}</span>

					<span slot="ptype" slot-scope="text, record" style="">
						{{ ptypeFilter(record.ptype) }}
					</span>

					<span slot="is_pickup" style="" slot-scope="text, record">{{
						record.is_pickup == 1 ? "是" : "否"
					}}</span>

					<span slot="payer" style="" slot-scope="text, record">{{
						payerFilter(record.payer)
					}}</span>

					<span slot="pay_time" style="" slot-scope="text, record">{{
						formatDate(record.pay_time)
					}}</span>

					<span slot="create_time" style="" slot-scope="text, record">{{
						formatDate(record.create_time)
					}}</span>

					<!-- <span slot="memo_content" style="" slot-scope="text, record">{{
						record.memo
					}}</span> -->

					<span slot="action" slot-scope="text, record">
						<template>
							<a @click="getDetail(record)" v-has="'order.select'">查看</a>
							<!-- <a-divider type="vertical" /> -->
							<!-- <a @click="updateOrder(record)">修改</a> -->
						</template>
					</span>
				</a-table>
			</div>
		</a-layout-content>
	</a-layout>
</template>


<script>
	import tableObj from "../json/table.json"
	import orderHttp from "@/api/order"
	import salemarket from "@/api/salemarket"
	console.log(tableObj)
	export default {
		name: "history",

		data() {
			this.payStatusMap = {
				"-1": {
					text: "支付失败",
				},
				0: {
					text: "未支付",
				},
				1: {
					text: "支付成功",
				},
				2: {
					text: "支付中",
				},
				3: {
					text: "上海订单(挂起的订单)",
				},
			}
			this.productList = {
				1: "场内转运",
				2: "场内装卸",
				3: "同城配送",
			}
			this.payerMap = {
				1: {
					text: "寄付",
				},
				2: {
					text: "到付",
				},
			}
			this.orderTypeMap = {
				1: {
					text: "场内订单",
					// status: "default",
				},
				2: {
					text: "场外订单",
					// status: "default",
				},
				3: {
					text: "tms订单",
					// status: "default",
				},
			}
			this.statusMap = {
				// 1: {
				// 	// status: "success",
				// 	text: "推送cp/tms成功",
				// },
				2: {
					// status: "default",
					text: "已分配",
				},

				3: {
					// status: "default",
					text: "待揽收",
				},
				4: {
					// status: "default",
					text: "配送中",
				},
				5: {
					// status: "default",
					text: "已完成",
				},

				6: {
					// status: "default",
					text: "已拒收",
				},

				0: {
					// status: "default",
					text: "已下单",
				},
				"-1": {
					// status: "error",
					text: "已取消",
				},
			}
			return {
				loading: false,
				columns: tableObj.columns,
				data: [
					// {
					// 	status: 2,
					// 	order_type: 2,
					// 	is_pickup: 1,
					// },
				],

				// ========================================
				// 查询参数
				created_at_range: [],
				marketData: [],
				queryForm: {
					created_at_range: undefined,
					order_no: undefined,
					status: undefined,
					pay_status: undefined,
					merchant_name: undefined,
					market_id: undefined,
					ptype: undefined,
					order_tag: 4,
				},
				currentPage: 1,

				pagination: {
					current: 1,
					pageSize: 20,
					total: 0,
					totalPage: 0,
					showSizeChanger: true,
					showTotal: (total) => `总 ${total} 条`,
				},
				form: {
					//订单号
					//订单状态
					// -1 已取消
					// 0 下单成功(已创建)
					// 1 推送cp/tms成功
					// 2 订单已分配
					// 3 订单待揽收(转运手已接受)
					// 4 已揽收配送中(转运手已收货)
					// 5 已签收
					// 6 已拒收
				},

				labelCol: { span: 4 },
				wrapperCol: { span: 14 },
				other: "",
				rules: {
					name: [
						{
							message: "Please input Activity name",
							trigger: "blur",
						},
						{
							min: 3,
							max: 5,
							message: "Length should be 3 to 5",
							trigger: "blur",
						},
					],
					region: [
						{
							required: true,
							message: "Please select Activity zone",
							trigger: "change",
						},
					],
					date1: [
						{ required: true, message: "Please pick a date", trigger: "change" },
					],
					type: [
						{
							type: "array",
							required: true,
							message: "Please select at least one activity type",
							trigger: "change",
						},
					],
					resource: [
						{
							required: true,
							message: "Please select activity resource",
							trigger: "change",
						},
					],
					desc: [
						{
							required: true,
							message: "Please input activity form",
							trigger: "blur",
						},
					],
				},
				collect: {
					orders: 0,
					qty: 0,
					actualQty: 0,
				},
			}
		},

		created() {
			this.getData()
			// 获取批发市场列表
			this.getMarketList()
		},

		filters: {},

		computed: {
			rowSelection() {
				return {
					onSelect(record, selected, selectedRows, nativeEvent) {
						console.log(record, selected, selectedRows, nativeEvent)
					},
				}
			},
		},

		methods: {
			async getMarketList(params = {}) {
				// this.resetFormFields()
				this.marketData = []

				await salemarket.query(params).then((response) => {
					console.log("市场列表数据", response)
					if (response.code !== 1) {
						this.$message.warning(response.message)
						return
					}

					if (response.data && response.data.length > 0) {
						this.marketData = response.data.map((item) => {
							return {
								id: item.id,
								name: item.name,
							}
						})
					}
				})
			},
			handleMarketChange(market_id) {
				this.queryForm.market_id = market_id
				this.search()
			},
			reload() {
				window.location.reload()
			},
			exportTable() {
				// this.$excelUtil.genTable({
				// 	excelName: `${this.$route.meta.title}`,
				// 	columns: tableObj.columns,
				// 	tableData: this.handleOriginData(this.data),
				// 	filterKeys: ["action"],
				// })

				// let pageMap = {
				// 	page: this.pagination.current,
				// 	pageSize: this.pagination.pageSize,
				// }

				// console.log(Object.assign(pageMap, this.queryForm))
				orderHttp
					// .export(Object.assign(pageMap, this.queryForm))
					.export(Object.assign({}, this.queryForm))
					.then((response) => {
						let link = document.createElement("a")
						let blob = new Blob([response], {
							type: "application/vnd.ms-excel",
						})
						link.style.display = "none"
						link.href = URL.createObjectURL(blob)
						link.setAttribute("download", `历史订单列表.csv`)
						document.body.appendChild(link)
						link.click()
						document.body.removeChild(link)
					})
					.catch((err) => {
						console.log(err)
					})
			},
			//解析数据中不能识别部分
			// handleOriginData(data) {
			// 	return data.map((item) => {
			// 		return Object.assign({}, item, {
			// 			status: this.statusFilter(item.status),
			// 			ptype: this.ptypeFilter(item.ptype),
			// 			is_pickup: item.is_pickup == 1 ? "是" : "否",
			// 			payer: this.payerFilter(item.payer),
			// 			create_time: this.formatDate(item.create_time),
			// 			pay_time: this.formatDate(item.pay_time),

			// 			// status: this.statusMap[item.status + ""].text,
			// 			// created_at: this.formatDate(item.created_at),
			// 			// updated_at: this.formatDate(item.updated_at),
			// 		})
			// 	})
			// },
			ptypeFilter(ptype) {
				if (["", "undefined", "null", "NaN", "false"].includes(ptype + "")) return
				return this.productList[ptype + ""]
			},
			// calcTableWidth(columns) {
			// 	let totalWidth = 0
			// 	for (let i = 0, len = columns.length; i < len; i++) {
			// 		if (columns[i].width) {
			// 			totalWidth += columns[i].width
			// 		} else {
			// 			totalWidth += 120
			// 		}
			// 	}
			// 	return totalWidth
			// },
			// 清空
			clear() {
				this.created_at_range = []
				this.queryForm = {
					created_at_range: undefined,
					order_no: undefined,
					status: undefined,
					pay_status: undefined,
					merchant_name: undefined,
					market_id: undefined,
					ptype: undefined,
					order_tag: 4,
				}

				this.getData()
			},
			// 搜索
			search() {
				this.data = []
				// this.pagination.current = 1
				this.pagination.current = 1
				this.getData()
			},
			handleTableChange(pagination, filters, sorter) {
				console.log(pagination, filters, sorter)
				if (sorter) {
					if (sorter.order) {
						Object.assign(this.queryForm, {
							order_by: `${sorter.columnKey} ${sorter.order.slice(0, -3)}`,
						})
					} else {
						delete this.queryForm.order_by
					}
				}
				this.pagination = pagination || this.pagination
				this.getData()
			},
			formatDate(timeStr) {
				if (["", "undefined", "null", "NaN", "false"].includes(timeStr + ""))
					return
				return this.$formatDate("Y-M-D h:m:s", +new Date(timeStr))
			},
			getDetail(record) {
				// this.$emit("handleDetail", record)
				this.$router.push("/order-history/detail/" + record.id)
			},
			payStatusFilter(pay_status) {
				if (["", "undefined", "null", "NaN", "false"].includes(pay_status + ""))
					return

				return this.payStatusMap[pay_status + ""]
					? this.payStatusMap[pay_status + ""].text
					: undefined
			},
			// updateOrder() {},
			statusFilter(status) {
				// console.log(status)

				if (["", "undefined", "null", "NaN", "false"].includes(status + ""))
					return
				return this.statusMap[status + ""]
					? this.statusMap[status + ""].text
					: undefined
			},
			// statusTypeFilter(status) {
			// 	console.log(status)
			// 	return this.statusMap[status + ""].status
			// },
			payerFilter(payer) {
				if (["", "undefined", "null", "NaN", "false"].includes(payer + "")) return
				// console.log(payer)
				return this.payerMap[payer + ""]
					? this.payerMap[payer + ""].text
					: undefined
			},
			orderFilter(status) {
				if (["", "undefined", "null", "NaN", "false"].includes(status + ""))
					return
				// console.log(status)
				return this.orderTypeMap[status + ""]
					? this.orderTypeMap[status + ""].text
					: undefined
			},
			// orderTypeFilter(status) {
			// 	console.log(status)
			// 	return this.orderTypeMap[status + ""].status
			// },

			onChange(created_at_range) {
				console.log(created_at_range)
				if (created_at_range && created_at_range.length === 0) {
					this.created_at_range = []
					this.queryForm.created_at_range = undefined
					return
				}
				this.created_at_range = created_at_range
				this.queryForm.created_at_range =
					created_at_range[0].format("YYYY-MM-DD") +
					"_" +
					created_at_range[1].format("YYYY-MM-DD")
			},
			// onSubmit() {
			// 	this.$refs.ruleForm.validate((valid) => {
			// 		if (valid) {
			// 			alert("submit!")
			// 		} else {
			// 			console.log("error submit!!")
			// 			return false
			// 		}
			// 	})
			// },
			// resetForm() {
			// 	this.$refs.ruleForm.resetFields()
			// },

			getData() {
				this.loading = true

				// 基本参数
				let pageMap = {
					page: this.pagination.current,
					pageSize: this.pagination.pageSize,
				}

				console.log(Object.assign(pageMap, this.queryForm))

				orderHttp
					.query(this.$removeField(Object.assign(pageMap, this.queryForm)))
					.then((res) => {
						console.log(res)
						this.loading = false
						if (res.code == 1) {
							this.pagination.total = res.page.totalSize
							this.pagination.totalPage = res.page.totalPage

							this.collect = {
								orders: res.statistics.order_count,
								qty: res.statistics.qty,
								actualQty: res.statistics.actual_qty,
							}

							this.data = res.data

							//dataSource 默认将每列数据的 key 属性作为唯一的标识
							//处理数据，否则需要excel代码里处理了
							// this.data = res.data.map((item, index) => {
							// 	return Object.assign(item, { index: index + 1 })
							// })
							// // ========================
							// if (this.data.length === 0) {
							// 	this.data = [
							// 		{ id: "1", name: "a" },
							// 		{ id: "2", name: "b" },
							// 	]
							// }
							// ========================
							// console.log(this.data)
							// console.log(this.pagination)
						}
					})
					.catch((e) => {
						this.loading = false
					})
			},
			handleData(item, index) {
				// const payments = {
				// 	1: "寄付",
				// 	2: "寄付",
				// }
				// const orderTypes = {
				// 	1: "场内订单",
				// 	2: "场外订单",
				// 	3: "tms订单",
				// }
				// item.index = index + 1
				// item.key = item.id
				// item.payment = payments[item.payer]
				// item.orderType = orderTypes[item.order_type]
				// item.pickup = item.is_pickup ? "是" : "否"
				// item.createTimes = item.created_at_show.split(" ")
				// item.orderMemo = item.memo || "暂无"
			},
		},
	}
</script>

<style lang="less" >
	.order-history {
		.form {
			margin: 0 24px 10px;
			padding: 10px 20px 20px;
			background: #fff;
			.ant-row {
				&:last-child {
					padding-top: 10px;
				}
			}
		}

		.table {
			margin: 10px 24px;
		}
		.table-toolBar {
			margin-bottom: 8px;
			font-size: 12px;
			color: rgba(112, 112, 112, 1);
		}
	}
</style>